package storage

import (
	"gitee.com/mkwchecking/sr-core/log"
	"gitee.com/mkwchecking/sr-core/storage/cache"
	"gitee.com/mkwchecking/sr-core/storage/database"
	"gitee.com/mkwchecking/sr-core/storage/database/driver"

	_ "gitee.com/mkwchecking/sr-core/storage/cache/register"
)

var instance = newDefaultStorage()

func Install(dbCfg *driver.Config, cacheCfg *cache.Config, logger log.Logger) (IStorage, error) {
	if _, err := InstallDB(dbCfg, logger); err != nil {
		return nil, err
	}

	if _, err := InstallCache(cacheCfg); err != nil {
		return nil, err
	}
	return instance, nil
}

func InstallDB(dbCfg *driver.Config, logger log.Logger) (IStorage, error) {
	if instance != nil {
		return instance, nil
	}

	db, err := database.Install(dbCfg, logger)
	if err != nil {
		return nil, err
	}

	instance.SetDataSet(db)

	return instance, nil
}

func InstallCache(cacheCfg *cache.Config) (IStorage, error) {
	if instance != nil {
		return instance, nil
	}

	cache, err := cache.Install(cacheCfg)
	if err != nil {
		return nil, err
	}

	instance.SetCache(cache)

	return instance, nil
}
